<template>
  <div class="v-model-tree">
    <div class="_model-tree-header">
      <ToolBar @toggle-siderbar="toggleSiderbar"></ToolBar>
      <!-- <button @click="handleUndo">undo</button>
      <button @click="handleRedo">redo</button> -->
    </div>
    <div
      v-if="isExpand"
      class="search_Banner"
      :class="{ isExpand: isExpand }"
    >
      <SearchNode
        :searchInSiderBodyTree="true"
        @selectNode="onSearchSelect"
      />
    </div>
    <div
      ref="scrollContainer"
      class="g-flex-1 g-ov-auto g-pd-8 g-pd-b-12"
      @scroll="handleScroll"
    >
      <!-- <MDropdown hide-on-scroll>
        <span >Button</span>
        <template #dropdown>
          <div>666666666666666666666</div>
        </template>
      </MDropdown> -->
      <m-tree
        :treeData="treeData"
        :load-nodes="(loadNodes as any)"
        disable-keyboard
        lazy
        custom-load-result
      >
        <template #default="{ nodeData }">
          <m-model-tree-node
            :graphNode="nodeData"
            :lock-name="showPackageLockName(nodeData)"
            :commentLevel="treeCommentStat?.[nodeData.id] ?? undefined"
          />
          <!-- <span >
            <img :src="nodeData.data.icon"/>
            <span class="g-m-l-4">
              {{nodeData.data.name}}
            </span>
          </span> -->
        </template>
      </m-tree>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { watch, ref, computed, onMounted } from "vue";
import MTree from "@/common/Tree/MTree.vue";
// import { GraphNode, NodeData } from "@/project/GraphNode";
import MModelTreeNode from "./TreeNode.vue";
import { GraphNode } from "@/modules/model/project/GraphNode";
import ToolBar from "./TreeToolBar.vue";
import { ActionKey } from "@/action/ActionKey";
import SearchNode from "@/common/SearchModel/SearchNode.vue";
import { ModelData } from "@/constants/types";
import { ModelFrom } from "@/constants/Enums";
import { SelectOnTreeAction } from "@/modules/model/actions/common/SelectOnTreeAction";

const scrollContainer = ref<HTMLDivElement>();

const isExpand = ref(false);
const treeData = computed(() => {
  return app.activeProject?.nodePool.rootNodes || [];
});

function toggleSiderbar(value: string) {
  if (value === ActionKey.search) {
    isExpand.value = !isExpand.value;
  }
}
/**
 * 是否显示包被锁定，自己锁定不回显
 */
const showPackageLockName = computed(() => {
  return (node: GraphNode) => {
    if (app.activeProject?.config && app.activeProject.config.onlineConfig) {
      const packageStatus = app.activeProject.config.onlineConfig.packageStatus[node.id];
      if (packageStatus && packageStatus.LOCKED) {
        if (packageStatus.LOCK_USER_NAME) {
          return `[${packageStatus.LOCK_USER_NAME}]`;
        }
      }
    }
    return "";
  };
});

const treeCommentStat = computed(() => {
  if (!app.projectManager?.activeProject?.ui.isShowComment) return {};
  return app.activeProject?.commentModel?.commentTreeModel.value || {};
});

async function loadNodes(node: GraphNode): Promise<void> {
  const activeProject = app.activeProject;
  if (!activeProject) throw new Error("not active project");

  await activeProject.nodePool.loadNodes(node);
}

async function handleScroll(evt: Event) {
  const modelTreeScroll = app.activeProject?.ui.modelTreeScroll;
  if (!modelTreeScroll) return;
  modelTreeScroll.top = (evt.target as HTMLDivElement).scrollTop;
  modelTreeScroll.left = (evt.target as HTMLDivElement).scrollLeft;
}

function resumeScroll() {
  const modelTreeScroll = app.activeProject?.ui.modelTreeScroll;
  if (!modelTreeScroll) return;
  if (top) {
    if (scrollContainer.value) {
      scrollContainer.value.scrollTop = modelTreeScroll.top;
      scrollContainer.value.scrollLeft = modelTreeScroll.left;
    }
  }
}

async function onSearchSelect(id: string, model: ModelData) {
  if (
    app.activeProject &&
    !app.activeProject!.ui.showProfileOnModelTree &&
    [ModelFrom.SYSTEM_PROFILE, ModelFrom.IMPORT_PROFIEL].includes(model.from)
  ) {
    const res = await app.$confirm.popup({
      title: "提示",
      subTitle: `文件已被隐藏，是否展示扩展文件？`,
      cancelText: "取 消",
      okText: "确 定",
      status: "warn"
    });
    const type = res.type as string;
    if (type === "ok") {
      app?.activeProject?.ui.showExpandFile(true);
    } else {
      return;
    }
  }

  const action = app.actionManager.getAction(ActionKey.selectOnTree) as SelectOnTreeAction;

  action?.run([id], {
    scroll: true,
    changeTab: false,
    isModelLibrary: false,
    modelLibraryProjectId: ""
  });
}
onMounted(() => {
  resumeScroll();
});

watch(
  () => app.projectManager.activeProjectId,
  () => {
    setTimeout(() => {
      resumeScroll();
    }, 0);
  }
);
</script>
<style lang="scss">
.v-model-tree {
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  ._model-tree-header {
    height: 29px;
    flex: 0;
  }
  .search_Banner {
    width: 100%;
    height: 0px;
    opacity: 0;
    transition: all 0.5s;
  }
  .isExpand {
    height: 30px;
    opacity: 100;
  }
}
</style>
